package zhongbo.java.air.common.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import zhongbo.java.air.common.exception.BusinessException;
import zhongbo.java.air.common.exception.ExceptionCode;
import zhongbo.java.air.common.exception.NoStackLogException;
import zhongbo.java.air.common.util.HttpServletUtil;
import zhongbo.java.air.common.vo.ResultVo;

import javax.servlet.http.HttpServletRequest;

/**
 * 说明：异常统一管理
 * <p>
 * #@ControllerAdvice
 * 增强Controller注解, 使用场景:
 * 1.全局异常处理
 * 2.全局数据绑定
 * 3.全局数据预处理
 * <p>
 *
 * @author 钟波notebook
 * @see <a href="https://www.cnblogs.com/gdwkong/articles/8660002.html">8660002.html</a>
 * @since 2020年01月20日 星期一 18:27:55
 */
@ControllerAdvice
@Slf4j
public class AllExceptionHandler {

    /**
     * 判断错误是否是已定义的已知错误，不是则由未知错误代替，同时记录在log中
     *
     * @param e Exception
     * @return JsonRespDto
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResultVo<Object> exceptionGet(Exception e) {
        HttpServletRequest request = HttpServletUtil.getRequest();
        log.error("【系统异常】 {}", e.getMessage(), e);
        return ResultVo.error(e.getMessage());
    }

    /**
     * 判断错误是否是已定义的已知错误，不是则由未知错误代替，同时记录在log中
     *
     * @param e Exception
     * @return JsonRespDto
     */
    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public ResultVo<Object> exceptionGet(BusinessException e) {
        HttpServletRequest request = HttpServletUtil.getRequest();
        ExceptionCode exceptionCode = e.getCode();
        Integer code = exceptionCode.getCode();
        String msg = exceptionCode.getMsg();
        log.error("【{}】 {}", e.getCode().getMsg(), e.getMessage(), e);
        String errorMsg = String.format("【%s】 %s", msg, e.getMessage());
        return ResultVo.wrong(code, errorMsg);
    }

    /**
     * 判断错误是否是已定义的已知错误，不是则由未知错误代替，同时记录在log中
     *
     * @param e Exception
     * @return JsonRespDto
     */
    @ExceptionHandler(value = NoStackLogException.class)
    @ResponseBody
    public ResultVo<Object> exceptionGet(NoStackLogException e) {
        HttpServletRequest request = HttpServletUtil.getRequest();
        ExceptionCode exceptionCode = e.getCode();
        Integer code = exceptionCode.getCode();
        String msg = exceptionCode.getMsg();
        log.error("【{}】 {}", e.getCode().getMsg(), e.getMessage());
        String errorMsg = String.format("【%s】 %s", msg, e.getMessage());
        return ResultVo.wrong(code, errorMsg);
    }

}
